package com.googlecode.tidej.client;

import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;

public class Dialog extends DialogBox {
  FlowPanel rootPanel = new FlowPanel();
  FlowPanel contentPanel = new FlowPanel();
  FlowPanel buttonPanel = new FlowPanel();
  Button cancelButton = new Button("Cancel");

  ClickHandler cancelHandler = new ClickHandler() {
    @Override
    public void onClick(ClickEvent event) {
      Dialog.this.hide();
    }
  };
  
  
  public Dialog(String title) {
    setText(title);
    rootPanel.add(contentPanel);
    rootPanel.add(buttonPanel);
    addButton(cancelButton);
    Label cancelField = new HTML("<b>\u00d7</b>");
    Style style = cancelField.getElement().getStyle();
    style.setPosition(Position.ABSOLUTE);
    style.setTop(5, Unit.PX);
    style.setRight(20, Unit.PX);
    rootPanel.add(cancelField);
    cancelField.addClickHandler(cancelHandler);
    cancelButton.addClickHandler(cancelHandler);
    buttonPanel.getElement().setAttribute("style", "text-align:right;border-top:1px solid #ccc;padding:8px 4px;margin-top:5px");
    setWidget(rootPanel);
  }

  
  public FlowPanel getContentPanel() {
    return contentPanel;
  }
  
  public void addButton(Button button) {
    button.getElement().getStyle().setMarginLeft(4, Unit.PX);
    buttonPanel.add(button);
  }

  public static boolean checkName(String title, String name) {
    if (name == null || name.length() == 0) {
      Window.alert(title + " must not be empty.");
      return false;
    }
    if (name.charAt(0) >= '0' && name.charAt(0) <= '9') {
      Window.alert(title + " must not start with a digit.");
      return false;
    }
    for (int i = 0; i < name.length(); i++) {
      char c = name.charAt(i);
      if (c != '_' && (c < 'a' || c > 'z') && (c < '0' || c > '9') && (c < 'A' && c > 'Z')) {
        Window.alert(title + " must not contain non-identifier character '" + c + "'.");
        return false;
      }
    }
    return true;
  }

}
